<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use app\helpers\Time;
/**
 * This is the model class for table "auction".
 *
 * @property integer $auctionid
 * @property integer $product_id
 * @property double $market_val
 * @property double $cost
 * @property double $return_rate
 * @property double $start_price
 * @property double $scope
 * @property double $fee
 * @property integer $degree
 * @property double $lowest_price
 * @property double $highest_price
 * @property double $default_price
 * @property integer $actcount
 * @property integer $reacount
 * @property integer $can_robot
 * @property integer $have_cost
 * @property integer $can_give
 * @property integer $periods
 * @property integer $state
 * @property integer $user_id
 * @property string $nickname
 * @property integer $price
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $end_at
 * @property \app\models\Product $product
 */
class Auction extends ActiveRecord
{
    const CAN_ROBOT = 1;
    const NOT_ROBOT = 0;

    const STATE_READY = 2;
    const STATE_IS_AUCTION = 1;
    const STATE_NOT_AUCTION = 0;

    const CAN_GIVE = 1;
    const NOT_GIVE = 0;

    const HAVE_COST = 1;
    const NOT_COST = 0;

    public static function dropdown($column, $value = null)
    {
        $dropDownList = [
            'can_give'=>[
                self::CAN_GIVE =>'可以使用赠币',
                self::NOT_GIVE=>'只能使用拍币'
            ],
            'can_robot'=> [
                self::CAN_ROBOT=>'机器人拍中',
                self::NOT_ROBOT=>'用户拍中',
            ],
            'state'=>[
                self::STATE_READY =>'准备开始',
                self::STATE_IS_AUCTION=>'竞拍中',
                self::STATE_NOT_AUCTION=>'竞拍结束',
            ],
            'have_cost'=>[
                self::HAVE_COST =>'考虑成本',
                self::NOT_COST=>'不考虑成本',
            ]
        ];
        if ($value !== null)
            return array_key_exists($column, $dropDownList) ? $dropDownList[$column][$value] : false;
        else
            return array_key_exists($column, $dropDownList) ? $dropDownList[$column] : false;
    }
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes'=>[
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ]
        ];
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'auction';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id', 'market_val', 'cost', 'return_rate', 'start_price', 'scope', 'fee', 'degree', 'lowest_price', 'highest_price', 'default_price', 'actcount', 'reacount', 'can_robot', 'have_cost', 'can_give', 'periods', 'state', 'user_id', 'nickname', 'price', 'end_at'], 'required'],
            [['product_id', 'degree', 'actcount', 'reacount', 'can_robot', 'have_cost', 'can_give', 'periods', 'state', 'user_id', 'created_at'], 'integer'],
            [['market_val', 'cost', 'return_rate', 'start_price', 'scope', 'fee', 'lowest_price', 'highest_price', 'default_price'], 'number'],
            [['nickname', 'price'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'auctionid' => 'ID',
            'product_id' =>'产品',
            'market_val' => '市场价',
            'cost' => '成本价',
            'return_rate' => '退还率',
            'start_price' => '起拍价',
            'scope' => '涨幅',
            'fee' => '单次加价手续费',
            'degree' => '默认竞拍次数',
            'lowest_price' => '最低成交价',
            'highest_price' => '最高成交价',
            'default_price' => '默认成交价',
            'actcount' => '竞拍倒计时',
            'reacount' => '准备开始倒计时',
            'can_robot' => '拍中对象',
            'have_cost' => '考虑成本',
            'can_give' => '可以使用赠币',
            'periods' => '期数',
            'state' => '状态',
            'user_id' => '拍中人id',
            'nickname' => '拍中人昵称',
            'price' => '成交价',
            'created_at' => '创建时间',
            'updated_at' => '修改时间',
            'end_at' => '结束时间',
        ];
    }
    //准备开始
    public static function ready(Product $product,$oldModel = null)
    {
        /** @var  $oldModel self*/
        $oldModel = $oldModel?$oldModel:self::find()->where([
            'product_id'=>$product->pid,
        ])->orderBy(['created_at'=>SORT_DESC])->one();
        if($oldModel&&$oldModel->state != self::STATE_NOT_AUCTION)//如果产品处于活跃状态，则不添加新的竞拍
            return $oldModel;
        $model = new self();
        $model->product_id = $product->pid;
        $model->market_val = $product->market_val;
        $model->cost = $product->cost;
        $model->return_rate = $product->return_rate;
        $model->start_price = $product->start_price;
        $model->scope = $product->scope;
        $model->price = $product->start_price;
        $model->fee = $product->fee;
        $model->degree = $product->degree;
        $model->lowest_price = $product->lowest_price;
        $model->highest_price = $product->highest_price;
        $model->default_price = rand($product->lowest_price*10,$product->highest_price*10)/10;
        $model->actcount = $product->actcount;
        $model->reacount = $product->reacount;
        $model->can_robot = $product->can_robot;
        $model->have_cost = $product->have_cost;
        $model->can_give = $product->can_give;
        $model->periods = $oldModel?$oldModel->periods+1:1;
        $model->state = self::STATE_READY;
        $model->save(false);
        return $model;
    }
    //开始
    public function start(){
        if($this->state == self::STATE_READY){
            $this->state = self::STATE_IS_AUCTION;
            $this->save(false);
        }
    }
    //结束
    public function end()
    {
        //清除队列
        BidSericesqueue::deleteAll(['auction_id'=>$this->auctionid]);
        BidQueue::deleteAll(['auction_id'=>$this->auctionid]);
        /* @var $topRcd BidRcd*/
        $topRcd = BidRcd::find()->where(['auction_id'=>$this->auctionid])->orderBy(['price'=>SORT_DESC])->one();
        if($topRcd){
            /** @var  $users User[]*/
            $users = User::find()->indexBy('userid')->where(['type'=>User::IS_USER])->all();
            $this->user_id = $topRcd->user_id;
            $this->state = self::STATE_NOT_AUCTION;
            $this->nickname = $topRcd->user->name;
            $this->end_at = time();
            $this->save(false);
            if(isset($users[$this->user_id])){//是人则推送消息
                $product = $this->product;
                Push::create(
                    '您已拍中商品',
                    "您以{$this->price}的价格拍中了商品{$product->name}{$product->spec},请在订单列表中查看拍中信息",
                    $this->user_id,
                    Push::TYPE_AUCTION
                );
            }
            /** @var  $orders Saleorder[] */
            $orders = Saleorder::find()->where(['auction_id'=>$this->auctionid])->all();

            foreach($orders as $order)
            {
                if($order->user_id == $this->user_id){
                    $order->out_trade_no = $order->build_order_no();//拍中即可支付，需要流水号
                    $order->state = Saleorder::STEAT_PATTED;
                    $order->save(false);
                }else{
                    if(isset($users[$order->user_id])){//用户
                        $user = $users[$order->user_id];
                        $give_money = $this->return_rate*$this->fee*$order->num;
                        $user->give_money+=$give_money;
                        $user->save(false);
                        $order->state = Saleorder::STEAT_NOT_PATTED;
                        $order->save(false);
                        Bill::log('未拍中回退',$give_money,$order->user_id);
                    }else{//机器人未拍中订单为无用数据，删除
                        $order->delete();
                    }
                }
            }
            self::ready($this->product,$this);
        }
    }
    /**
     * 获取首个竞拍数组
     * @return static[]
     */
    public static function getFirsts()
    {
        $key = 'getFirsts';
        if (!Yii::$container->has($key)) {
            $first_auctions = static::find()
                ->where(['state'=>self::STATE_IS_AUCTION])
                ->orderBy(['product_id'=>SORT_DESC])
                ->indexBy('product_id')
                ->all();
            $stdClass = new \stdClass();
            $stdClass->objects = $first_auctions;
            Yii::$container->set($key, $stdClass);
        }
        $data = Yii::$container->get($key)->objects;
        return $data;
    }

    public static function getFirst($product_id)
    {
        $first_auction = static::find()->where(['product_id'=>$product_id])->orderBy(['created_at'=>SORT_DESC])->one();
        if(!$first_auction){
            $product = Product::findOne($product_id);
            $first_auction = static::ready($product);
        }
        return $first_auction;
    }

    public function getProduct()
    {
        return $this->hasOne(Product::className(),['pid'=>'product_id']);
    }

    public function getBidRcds()
    {
        return $this->hasMany(BidRcd::className(),['auction_id'=>'auctionid']);
    }
}
